package com.zhenyi.youqu.miniapp;

import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.youqu.common.model.YqCart;
import com.youqu.common.model.YqProduct;
import com.youqu.common.model.YqProductFormat;
import com.youqu.common.model.YqUser;
import com.zhenyi.youqu.core.YQMiniAppController;
import com.zhenyi.youqu.interceptor.YQUserInterceptor;

/**
 * 购物车模块
 * 
 * @author Frank Cen at home2019年3月5日 上午1:07:57
 *
 */
public class CartController extends YQMiniAppController {

	/**
	 * 我的购物车
	 */
	@Before({ YQUserInterceptor.class })
	public void cart() {
		YqUser user = getUser();
		Kv kv = Kv.by("userId", user.getId());
		SqlPara sqlPara = db.getSqlPara("YQCartProducts", kv);
		Page<Record> pages = db.paginate(getPage(), getPageSize(), sqlPara);
		renderPage(pages);
	}

	/**
	 * 我的购物车
	 */
	@Before({ YQUserInterceptor.class })
	@Override
	public void list() {
		YqUser user = getUser();
		Kv kv = Kv.by("userId", user.getId());
		SqlPara sqlPara = db.getSqlPara("YQCartProducts", kv);
		Page<Record> pages = db.paginate(getPage(), getPageSize(), sqlPara);
		for (Record record : pages.getList()) {
			Float formatFee = record.getInt("formatFee").floatValue();
			record.set("formatPrice", formatFee / 100f);
		}
		renderPage(pages);
	}

	/**
	 * 更新购物车,count为0则删除当前商品
	 */
	@Before({ YQUserInterceptor.class })
	@Override
	public void update() {
		Long productId = getParaToLong("productId");
		if (productId == null) {
			renderFailure("no productId");
			return;
		}
		YqProduct product = YqProduct.dao.findById(productId);
		if (product == null) {
			renderFailure("没有商品");
			return;
		}
		if (product.getIsGroup().equals(1)) {
			renderMsg("无法加入团购商品");
			return;
		}
		Long formatId = getParaToLong("formatId");
		if (formatId == null) {
			renderFailure("规格不存在");
			return;
		}
		Integer count = getParaToInt("count");
		if (count == null) {
			renderFailure("count error");
			return;
		}
		if (count <= 0) {
			count = 0;
		}
		YqProductFormat productFormat = YqProductFormat.dao.findById(formatId);
		if (productFormat == null) {
			renderFailure("format error");
			return;
		}
		if (!productFormat.getProductId().equals(productId)) {
			renderFailure("formatId not match");
			return;
		}
		YqUser user = getUser();
		Long userId = user.getId();
		YqCart cart = YqCart.dao.findById(formatId, productId, userId);
		if (cart == null) {
			if (count == 0) {
				renderMsg("数量为0");
				return;
			}
			cart = new YqCart();
			cart.setProductId(productId);
			cart.setUserId(userId);
			cart.setFormatId(formatId);
			if (!cart.save()) {
				renderFailure();
				return;
			}
		}
		if (count == 0) {
			if (!cart.delete()) {
				renderFailure();
				return;
			}
		} else {
			cart.setCount(count);
			if (!cart.update()) {
				renderFailure();
				return;
			}
		}
		renderSuccess();
	}

}
